package cn.cxg.ymcc.service.impl;

import cn.cxg.ymcc.MediaFeignAPI;
import cn.cxg.ymcc.SearchFeignAPI;
import cn.cxg.ymcc.constants.BusinessConstants;
import cn.cxg.ymcc.doc.CourseDoc;
import cn.cxg.ymcc.domain.*;
import cn.cxg.ymcc.dto.*;
import cn.cxg.ymcc.exception.GlobleException;
import cn.cxg.ymcc.mapper.CourseMapper;
import cn.cxg.ymcc.result.JSONResult;
import cn.cxg.ymcc.service.*;
import cn.cxg.ymcc.vo.CourseDetailVo;
import cn.cxg.ymcc.vo.CourseInfoResultVo;
import cn.cxg.ymcc.vo.CourseInfoVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale
 * @since 2025-08-10
 */
@Service
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private ICourseDetailService courseDetailService;

    @Autowired
    private ICourseMarketService courseMarketService;

    @Autowired
    private ICourseResourceService courseResourceService;

    @Autowired
    private ICourseTeacherService courseTeacherService;

    @Autowired
    private ICourseSummaryService courseSummaryService;

    @Autowired
    private ICourseChapterService courseChapterService;

    @Autowired
    private SearchFeignAPI searchFeignAPI;

    @Autowired
    private MediaFeignAPI mediaFeignAPI;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public void save(CourseSaveDto courseSaveDto) {
        //1.校验


        Course course = courseSaveDto.getCourse();
        CourseDetail courseDetail = courseSaveDto.getCourseDetail();
        CourseMarket courseMarket = courseSaveDto.getCourseMarket();
        CourseResource courseResource = courseSaveDto.getCourseResource();
        List<Long> teacharIds = courseSaveDto.getTeacharIds();


        //2.保存
        //course
        List<Teacher> teachers = teacherService.selectBatchIds(teacharIds);
        String teacherNames = teachers.stream().map(Teacher::getName).collect(Collectors.joining(","));
        course.setTeacherNames(teacherNames);
        course.setStatus(Course.OFFLINE);
        insert(course);

        //courseDetail
        courseDetail.setId(course.getId());
        courseDetailService.insert(courseDetail);

        //courseMarket
        courseMarket.setId(course.getId());
        courseMarketService.insert(courseMarket);

        //courseResource
        courseResource.setCourseId(course.getId());
        courseResourceService.insert(courseResource);

        //courseTeacher
        ArrayList<CourseTeacher> courseTeachers = new ArrayList<>();
        teacharIds.forEach(tid ->{
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setCourseId(course.getId());
            courseTeacher.setTeacherId(tid);
            courseTeachers.add(courseTeacher);

        });
        courseTeacherService.insertBatch(courseTeachers);


    }

    /**
     * 课程上线
     * @param courseIds
     */
    @Override
    public void onLineCourse(List<Long> courseIds) {
        // 1. 参数校验逻辑（Impl层手动校验）
        // 校验数组是否为空
        if (courseIds == null || courseIds.isEmpty()) {
            throw new GlobleException("请求异常");
        }

        //课程信息
        List<Course> courses = selectBatchIds(courseIds);

        //遍历课程信息获得status字段
        for (Course course : courses) {
            // 获取当前课程的status
            Integer status = course.getStatus();

            // 状态为0的处理逻辑（如：课程已下架）
            course.setStatus(Course.ONLINE);
            course.setOnlineTime(new Date());
            updateById(course);

        }

        //=========================================================
        List<CourseDoc> courseDocs = new ArrayList<>();
        courses.forEach(course -> {
            CourseDoc courseDoc = new CourseDoc();
            BeanUtils.copyProperties(course,courseDoc);

            CourseMarket courseMarket = courseMarketService.selectById(course.getId());
            BeanUtils.copyProperties(courseMarket,courseDoc);

//            CourseSummary courseSummary = courseSummaryService.selectById(course.getId());
//            BeanUtils.copyProperties(courseSummary,courseDoc);
            // 获取课程摘要
            CourseSummary courseSummary = courseSummaryService.selectById(course.getId());
            BeanUtils.copyProperties(courseSummary, courseDoc);



            courseDocs.add(courseDoc);
        });

        //调用搜索服务
        searchFeignAPI.save(courseDocs);
/*

        new Thread(() ->{
            publishMessage();
        }).start();
*/

    }

    /**
     * 课程详情页查询
     * @param courseId
     * @return
     */
    @Override
    public CourseDetailVo detail(Long courseId) {
        if(courseId==null){
            throw new GlobleException("请求参数异常");
        }

        CourseDetailVo detailVo = new CourseDetailVo();
        // 课程信息
        //private Course course;
        Course course = selectById(courseId);
        detailVo.setCourse(course);

        // 课程营销信息
        //private CourseMarket courseMarket;
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        detailVo.setCourseMarket(courseMarket);

        // 课程章节信息
        //private List<CourseChapter> courseChapters;
        //List<CourseChapter> courseChapters = courseChapterService.listByCourseId(courseId);

        Wrapper<CourseChapter> ww = new EntityWrapper<>();
        ww.eq("course_id",courseId);
        List<CourseChapter> courseChapters = courseChapterService.selectList(ww);

        // 课程id对应的视频
        JSONResult jsonResult = mediaFeignAPI.findByCourseId(courseId);
        String jsonStr = jsonResult.getData().toString();
        List<MediaFile> mediaFiles = JSONObject.parseArray(jsonStr, MediaFile.class);

        // 为什么空指针呢
        mediaFiles.forEach(mediaFile -> {
            courseChapters.forEach(courseChapter -> {
                if(mediaFile.getChapterId().longValue() == courseChapter.getId().longValue()){
                    courseChapter.getMediaFiles().add(mediaFile);
                }
            });
        });

        detailVo.setCourseChapters(courseChapters);

        // 中间表老师信息
        //private List<Teacher> teachers;
        List<Teacher> teachers = courseTeacherService.queryTeachersByCourseId(courseId);
        detailVo.setTeachers(teachers);

        //  课程详情信息
        //private Course courseDetail;
        CourseDetail courseDetail = courseDetailService.selectById(courseId);
        detailVo.setCourseDetail(courseDetail);

        // 课程概述信息
        //private Course courseSummary;
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        detailVo.setCourseSummary(courseSummary);
        return detailVo;
    }

    /**
     *查询订单回显
     * @param courseId
     * @return
     */
    @Override
    public CourseInfoResultVo courseInfo(String courseId) {
        if(StringUtils.isEmpty(courseId)){
            throw new GlobleException("请求参数异常");
        }
        // t_course 对传入的courseId进行切割，获取所有课程id
        String[] courseIds = courseId.split(",");
        List<Course> courses = selectBatchIds(Arrays.asList(courseIds));
        List<CourseMarket> courseMarkets = courseMarketService.selectBatchIds(Arrays.asList(courseIds));

        List<CourseInfoVo> courseInfoVos = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);
        for ( CourseMarket courseMarket : courseMarkets) {
            totalAmount = totalAmount.add(courseMarket.getPrice());
            for (Course cours : courses) {
                if(cours.getId().longValue()==courseMarket.getId().longValue()){
                    CourseInfoVo courseInfoVo = new CourseInfoVo(cours, courseMarket);
                    courseInfoVos.add(courseInfoVo);
                }
            }
        }

        CourseInfoResultVo courseInfoResultVo = new CourseInfoResultVo();
        courseInfoResultVo.setCourseInfos(courseInfoVos);
        courseInfoResultVo.setTotalAmount(totalAmount);
        return courseInfoResultVo;
    }


    private void publishMessage() {

        //站内消息
        MessageStationDto messageStationDto = new MessageStationDto();
        messageStationDto.setTitle("课程已发布");
        messageStationDto.setContent("尊敬的客服，我在骚扰你");
        messageStationDto.setType("系统信息");
        //模仿远程调用，查询用户id
        List<Long> userIds = Arrays.asList(1l, 2l, 3l, 4l, 5l, 6l);
        messageStationDto.setIds(userIds);

        SendResult sendResult = rocketMQTemplate.syncSend(BusinessConstants.ROCKETMQ_PUBLISH_TOPIC
                        + ":" + BusinessConstants.ROCKETMQ_STATION_TAGS,
                MessageBuilder.withPayload(JSONObject.toJSON(messageStationDto)).build());

        log.info("发送站内消息：{}",sendResult);



        //发送短信消息
        //        // 调用MQ,手机短信
        // @TODO   查询出用户和用户手机号对应的所有数据 略
        List<User2PhoneDto> list = Arrays.asList(
                new User2PhoneDto(1l,"13888888881"),
                new User2PhoneDto(2l,"13888888882"),
                new User2PhoneDto(3l,"13888888883"),
                new User2PhoneDto(4l,"13888888884"),
                new User2PhoneDto(5l,"13888888885")
        );
        MessageSmsDto messageSmsDto = new MessageSmsDto();
        messageSmsDto.setTitle("课程已发布");
        messageSmsDto.setContent("尊敬的客服，我在骚扰你-sms");
        messageSmsDto.setUser2PhoneDtos(list);
        SendResult smsResult = rocketMQTemplate.syncSend(
                BusinessConstants.ROCKETMQ_PUBLISH_TOPIC+":"+BusinessConstants.ROCKETMQ_SMS_TAGS,
                MessageBuilder.withPayload(JSONObject.toJSONString(messageSmsDto)).build());

        log.info("短信推送消息结果：{}",messageSmsDto);



        // 调用MQ,邮件推送
        List<User2EmailDto> list1 = Arrays.asList(
               new User2EmailDto(1l,"13888888881@qq.com"),
                new User2EmailDto(2l,"13888888882@qq.com"),
               new User2EmailDto(3l,"13888888883@qq.com"),
                new User2EmailDto(4l,"13888888884@qq.com"),
                new User2EmailDto(5l,"13888888885@qq.com")
        );
        MessageEmailDto messageEmailDto = new MessageEmailDto();
        messageEmailDto.setTitle("课程已发布");
        messageEmailDto.setContent("新课mq视频，很好");
        messageEmailDto.setUser2EmailDtos(list1);

        SendResult emailResult = rocketMQTemplate.syncSend(
                BusinessConstants.ROCKETMQ_PUBLISH_TOPIC+":"+BusinessConstants.ROCKETMQ_EMAIL_TAGS,
                MessageBuilder.withPayload(JSONObject.toJSONString(messageEmailDto)).build());
        log.info("邮件推送消息结果：{}",emailResult);
    }
}
